<template>
	<view class="orders-container">
		<!-- 订单状态筛选 -->
		<view class="status-tabs">
			<view 
				class="status-tab"
				:class="{ active: activeStatus === status.value }"
				v-for="status in statusOptions"
				:key="status.value"
				@click="switchStatus(status.value)"
			>
				{{ status.label }}
			</view>
		</view>

		<!-- 订单列表 -->
		<view class="orders-list">
			<view 
				class="order-card"
				v-for="order in orderList"
				:key="order.id"
				@click="goToOrderDetail(order.id)"
			>
				<!-- 订单头部 -->
				<view class="order-header">
					<text class="order-number">订单号: {{ order.orderNumber }}</text>
					<text class="order-status" :class="getStatusClass(order.status)">
						{{ getStatusText(order.status) }}
					</text>
				</view>

				<!-- 设备信息 -->
				<view class="device-info">
					<image :src="order.device.image" class="device-image" mode="aspectFill"/>
					<view class="device-details">
						<text class="device-name">{{ order.device.name }}</text>
						<text class="device-model">{{ order.device.model }}</text>
						<text class="rental-period">
							租期: {{ order.startDate }} - {{ order.endDate }}
						</text>
						<text class="total-amount">总计: ¥{{ order.totalAmount }}</text>
					</view>
				</view>

				<!-- 订单操作 -->
				<view class="order-actions">
					<u-button 
						v-if="order.status === 'SUBMITTED'"
						type="error" 
						size="small" 
						@click.stop="cancelOrder(order.id)"
					>
						取消订单
					</u-button>
					<u-button 
						v-if="order.status === 'CONFIRMED'"
						type="warning" 
						size="small"
						@click.stop="startRental(order.id)"
					>
						开始租赁
					</u-button>
					<u-button 
						v-if="order.status === 'IN_USE'"
						type="success" 
						size="small"
						@click.stop="returnDevice(order.id)"
					>
						归还设备
					</u-button>
					<u-button 
						type="info" 
						size="small"
						@click.stop="goToOrderDetail(order.id)"
					>
						查看详情
					</u-button>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view v-if="orderList.length === 0" class="empty-state">
			<image src="/static/empty-orders.png" class="empty-image"/>
			<text class="empty-text">暂无订单记录</text>
			<u-button type="primary" @click="goToDeviceList">去租赁设备</u-button>
		</view>

		<!-- 加载更多 -->
		<u-loadmore 
			v-if="orderList.length > 0"
			:status="loadStatus"
			@loadmore="loadMore"
		/>
	</view>
</template>

<script>
import apiService from '@/api/index.js'
import { checkLoginForTabPage } from '@/utils/auth.js'

export default {
	data() {
		return {
			activeStatus: 'ALL',
			statusOptions: [
				{ value: 'ALL', label: '全部' },
				{ value: 'SUBMITTED', label: '待确认' },
				{ value: 'CONFIRMED', label: '已确认' },
				{ value: 'IN_USE', label: '进行中' },
				{ value: 'COMPLETED', label: '已完成' },
				{ value: 'CANCELLED', label: '已取消' }
			],
			orderList: [],
			loadStatus: 'more',
			pagination: {
				page: 1,
				pageSize: 10
			}
		}
	},
	onLoad() {
		// 检查登录状态
		if (!checkLoginForTabPage()) {
			return
		}
		this.loadOrderList()
	},
	
	onShow() {
		// 检查是否刚刚登录成功，如果是则延迟加载避免token刷新冲突
		const justLoggedIn = uni.getStorageSync('just_logged_in')
		if (justLoggedIn) {
			console.log('🔄 刚刚登录，延迟加载订单数据...')
			uni.removeStorageSync('just_logged_in')
			setTimeout(() => {
				this.refreshOrderList()
			}, 500)
		} else {
			// 每次显示时刷新订单列表
			this.refreshOrderList()
		}
	},
	onPullDownRefresh() {
		this.refreshOrderList()
	},
	onReachBottom() {
		this.loadMore()
	},
	methods: {
		// 切换状态筛选
		switchStatus(status) {
			this.activeStatus = status
			this.refreshOrderList()
		},
		
		// 加载订单列表
		async loadOrderList() {
			try {
				this.loadStatus = 'loading'
				
				// 检查token是否存在
				const token = uni.getStorageSync('token')
				if (!token) {
					console.log('🚫 没有token，跳转登录页')
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/login/index'
						})
					}, 1500)
					return
				}
				
				// 构建查询参数
				const params = {
					page: this.pagination.page,
					limit: this.pagination.pageSize
				}
				
				// 添加状态筛选
				if (this.activeStatus !== 'ALL') {
					params.status = this.activeStatus
				}
				
				// 调用API获取订单列表
				const response = await apiService.order.getOrderList(params)
				
				// 处理响应数据格式
				let orders = []
				if (response.originalData && response.originalData.items) {
					orders = response.originalData.items
				} else if (response.data && response.data.items) {
					orders = response.data.items
				} else if (response.items) {
					orders = response.items
				} else if (Array.isArray(response.data)) {
					orders = response.data
				} else if (Array.isArray(response)) {
					orders = response
				}
				
				if (this.pagination.page === 1) {
					this.orderList = orders
				} else {
					this.orderList.push(...orders)
				}
				
				this.loadStatus = orders.length < this.pagination.pageSize ? 'nomore' : 'more'
				console.log('📋 订单列表加载成功:', orders.length + '条')
			} catch (error) {
				console.error('加载订单列表失败:', error)
				this.loadStatus = 'more'
				
				// 如果是Token刷新相关错误，不显示错误提示
				if (error.message && error.message.includes('Token已刷新')) {
					console.log('🔄 Token刷新相关错误，稍后自动重试')
					return
				}
				
				// 如果是401错误，跳转登录
				if (error.code === 401 || error.statusCode === 401) {
					console.log('🚫 Token无效，需要重新登录')
					uni.showToast({
						title: '登录已过期，请重新登录',
						icon: 'none'
					})
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/login/index'
						})
					}, 1500)
					return
				}
				
				// API调用失败时，显示空状态
				if (this.pagination.page === 1) {
					this.orderList = []
				}
				
				// 不弹出网络错误提示，保持静默失败，显示空状态
				console.log('订单加载失败，显示空状态')
			}
		},
		
		// 刷新订单列表
		refreshOrderList() {
			this.pagination.page = 1
			this.loadOrderList()
			uni.stopPullDownRefresh()
		},
		
		// 加载更多
		loadMore() {
			if (this.loadStatus === 'more') {
				this.pagination.page++
				this.loadOrderList()
			}
		},
		
		// 跳转到订单详情
		goToOrderDetail(orderId) {
			uni.navigateTo({
				url: `/pages/orders/detail?id=${orderId}`
			})
		},
		
		// 跳转到设备列表
		goToDeviceList() {
			uni.switchTab({
				url: '/pages/devices/list'
			})
		},
		
		// 取消订单
		async cancelOrder(orderId) {
			try {
				const result = await this.showConfirmDialog('确定要取消这个订单吗？')
				if (result.confirm) {
					uni.showLoading({ title: '处理中...' })
					
					// 调用取消订单API
					await apiService.order.updateOrderStatus(orderId, 'CANCELLED')
					
					uni.hideLoading()
					uni.showToast({ title: '订单已取消', icon: 'success' })
					this.refreshOrderList()
				}
			} catch (error) {
				console.error('取消订单失败:', error)
				uni.hideLoading()
				uni.showToast({ title: '取消失败', icon: 'none' })
			}
		},
		
		// 开始租赁
		async startRental(orderId) {
			try {
				uni.showLoading({ title: '处理中...' })
				
				// 调用开始租赁API
				await apiService.order.updateOrderStatus(orderId, 'IN_USE')
				
				uni.hideLoading()
				uni.showToast({ title: '租赁已开始', icon: 'success' })
				this.refreshOrderList()
			} catch (error) {
				console.error('开始租赁失败:', error)
				uni.hideLoading()
				uni.showToast({ title: '操作失败', icon: 'none' })
			}
		},
		
		// 归还设备
		async returnDevice(orderId) {
			try {
				const result = await this.showConfirmDialog('确定要归还设备吗？')
				if (result.confirm) {
					uni.showLoading({ title: '处理中...' })
					
					// 调用归还设备API
					await apiService.order.updateOrderStatus(orderId, 'COMPLETED')
					
					uni.hideLoading()
					uni.showToast({ title: '设备已归还', icon: 'success' })
					this.refreshOrderList()
				}
			} catch (error) {
				console.error('归还设备失败:', error)
				uni.hideLoading()
				uni.showToast({ title: '归还失败', icon: 'none' })
			}
		},
		
		// 获取状态样式类
		getStatusClass(status) {
			const statusMap = {
				'SUBMITTED': 'pending',
				'CONFIRMED': 'confirmed',
				'IN_USE': 'in-progress',
				'COMPLETED': 'completed',
				'CANCELLED': 'cancelled'
			}
			return statusMap[status] || 'pending'
		},
		
		// 获取状态文本
		getStatusText(status) {
			const statusMap = {
				'SUBMITTED': '待确认',
				'CONFIRMED': '已确认',
				'IN_USE': '进行中',
				'COMPLETED': '已完成',
				'CANCELLED': '已取消'
			}
			return statusMap[status] || '未知状态'
		},
		
		// 显示确认对话框
		showConfirmDialog(content) {
			return new Promise((resolve) => {
				uni.showModal({
					title: '确认操作',
					content,
					success: resolve
				})
			})
		},
		
		// 模拟数据
		getMockOrderList() {
			const statuses = ['SUBMITTED', 'CONFIRMED', 'IN_USE', 'COMPLETED', 'CANCELLED']
			return [
				{
					id: 1,
					orderNumber: 'MVR202401001',
					status: 'IN_USE',
					device: {
						name: 'MVR蒸发器-001',
						model: 'MVR-500L',
						image: '/static/device-sample.jpg'
					},
					startDate: '2024-01-15',
					endDate: '2024-01-25',
					totalAmount: 8000,
					createdAt: '2024-01-10 14:30:00'
				},
				{
					id: 2,
					orderNumber: 'MVR202401002',
					status: 'COMPLETED',
					device: {
						name: 'MVR蒸发器-002',
						model: 'MVR-1000L',
						image: '/static/device-sample.jpg'
					},
					startDate: '2024-01-01',
					endDate: '2024-01-10',
					totalAmount: 12000,
					createdAt: '2023-12-28 10:15:00'
				}
			].filter(order => 
				this.activeStatus === 'ALL' || order.status === this.activeStatus
			)
		}
	}
}
</script>

<style scoped>
.orders-container {
	background: #f5f5f5;
	min-height: 100vh;
}

.status-tabs {
	display: flex;
	background: white;
	border-bottom: 1rpx solid #f0f0f0;
	overflow-x: auto;
}

.status-tab {
	flex-shrink: 0;
	padding: 24rpx 32rpx;
	font-size: 28rpx;
	color: #666;
	text-align: center;
	border-bottom: 4rpx solid transparent;
	transition: all 0.3s;
}

.status-tab.active {
	color: #007aff;
	border-bottom-color: #007aff;
	font-weight: bold;
}

.orders-list {
	padding: 20rpx;
}

.order-card {
	background: white;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.order-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.order-number {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
}

.order-status {
	padding: 6rpx 16rpx;
	border-radius: 8rpx;
	font-size: 24rpx;
}

.order-status.pending {
	background: #fff7e6;
	color: #fa8c16;
}

.order-status.confirmed {
	background: #e6f7ff;
	color: #1890ff;
}

.order-status.in-progress {
	background: #f6ffed;
	color: #52c41a;
}

.order-status.completed {
	background: #f0f0f0;
	color: #666;
}

.order-status.cancelled {
	background: #fff2f0;
	color: #ff4d4f;
}

.device-info {
	display: flex;
	gap: 20rpx;
	margin-bottom: 20rpx;
}

.device-image {
	width: 120rpx;
	height: 120rpx;
	border-radius: 12rpx;
}

.device-details {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.device-name {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.device-model {
	font-size: 28rpx;
	color: #666;
}

.rental-period {
	font-size: 26rpx;
	color: #999;
}

.total-amount {
	font-size: 30rpx;
	font-weight: bold;
	color: #ff6600;
}

.order-actions {
	display: flex;
	gap: 20rpx;
	justify-content: flex-end;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 40rpx;
}

.empty-image {
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 40rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
	margin-bottom: 40rpx;
}
</style> 